package top.wilsonlv.jaguar.cloud.websocket.wrapper;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import top.wilsonlv.jaguar.cloud.websocket.sdk.WebsocketConstant;
import top.wilsonlv.jaguar.cloud.websocket.sdk.dto.WebsocketMessage;
import top.wilsonlv.jaguar.commons.web.util.WebUtil;
import top.wilsonlv.jaguar.security.model.SecurityUser;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author lvws
 * @since 2021/4/30
 */
@Slf4j
public class WebsocketSessionWrapper {

    @Getter
    private final WebSocketSession webSocketSession;

    @Getter
    private final String accessToken;

    @Getter
    private final String onlineKey;

    @Getter
    @Setter
    private LocalDateTime lastHeartBeatTime;


    public WebsocketSessionWrapper(WebSocketSession webSocketSession) {
        this.webSocketSession = webSocketSession;
        this.accessToken = WebUtil.getParam(Objects.requireNonNull(webSocketSession.getUri()), OAuth2AccessToken.ACCESS_TOKEN);
        this.onlineKey = String.format(WebsocketConstant.ONLINE_KEY_FORMAT, getUser().getId());
    }

    public String getId() {
        return webSocketSession.getId();
    }

    public SecurityUser getUser() {
        OAuth2Authentication authentication = (OAuth2Authentication) webSocketSession.getPrincipal();
        return authentication == null ? null : (SecurityUser) authentication.getPrincipal();
    }

    public boolean sendMessage(WebsocketMessage message) {
        synchronized (this.webSocketSession) {
            try {
                this.webSocketSession.sendMessage(new TextMessage(message.toJsonString()));
                return true;
            } catch (IOException e) {
                log.error("send websocket message error session : {}, username : {}", this.getId(), this.getUser().getUsername());
                return false;
            }
        }
    }

    public boolean pong() {
        return this.sendMessage(new WebsocketMessage(WebsocketConstant.MESSAGE_TYPE_PONG));
    }

}
